import { Spin, TreeSelect } from 'antd';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { useUpdateEffect } from 'ahooks';
import useProcessCatalogTree from '@/hooks/UseProcessCatalogTree';
import { findParentKeysRecursive } from '../CatalogTree';

function CatalogTreeSelect({ disableTreeNode, ...restProps }, ref) {
  const { value } = restProps;
  const { renderTree, loading: treeLoading, refresh, flattenData } = useProcessCatalogTree({
    disableTreeNode,
    withLeaves: false,
  });

  useImperativeHandle(ref, () => ({
    refresh,
  }));

  const [expandedKeys, setExpandedKeys] = useState([]);

  useUpdateEffect(() => {
    const nodesToSearch = flattenData.filter(node => node.catalogId === value);
    const parentKeys = findParentKeysRecursive(nodesToSearch, flattenData);
    setExpandedKeys(parentKeys);
  }, [flattenData]);

  return (
    <Spin spinning={treeLoading}>
      <TreeSelect
        treeExpandedKeys={expandedKeys}
        onTreeExpand={setExpandedKeys}
        placeholder="--请选择--"
        allowClear
        {...restProps}
      >
        {renderTree()}
      </TreeSelect>
    </Spin>
  );
}

export default forwardRef(CatalogTreeSelect);
